 <template>
	<div>
		<div style="display: flex; justify-content: center; align-items: center;">
		  <heart></heart>
		  <h1 style="margin-left: 25px;" class="title">登录</h1>
		</div>
		<el-form :model="loginform" ref="formObj" :rules="rules" style="margin-top: 50px;padding: 0 70px ; ">
			<el-form-item prop="username">
				<el-input :prefix-icon="User" v-model="loginform.username" placeholder="请输入手机号/电子邮箱"></el-input>
			</el-form-item>
			<el-form-item prop="password">
				<el-input :prefix-icon="Lock" v-model="loginform.password" placeholder="请输入登录密码" show-password></el-input>
			</el-form-item>
			<el-form-item>
				<el-checkbox v-model="checked.check" style="color: white;" label="记住密码(7天)"></el-checkbox>
				<el-link style="position: absolute; right: 0; color: white;" :underline="false" @click="$router.push('/password')">找回密码</el-link>
			</el-form-item>
			<el-form-item >
				<el-button style="width: 150px;" plain type="danger" @click="$router.push('/register')">注册</el-button>
				<el-button style="width: 150px;position: absolute; right: 0;"  plain type="danger" @click="login" >登录</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script setup>
import heart from '@/components/icons/heart'
import { post } from '@/axios'
import { _axios } from '@/axios'
import { userLoadingStore } from '@/stores'
import { User,Lock } from '@element-plus/icons-vue'
import { ElMessage,ElMessageBox } from 'element-plus'
import { ref,reactive } from 'vue'
import VueCookie from 'vue-cookie'
import router from '@/router'
import { userMenuStore, userIdStore, userAreaStore } from '@/stores'

const idStore = userIdStore()
const areaStore = userAreaStore()
const menuStore = userMenuStore()
const userLoading = userLoadingStore()

const validateUsername = ( rule, value,callback ) => {
  const emailPattern = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/
  const phonePattern = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/

  if (emailPattern.test(value)) {
    callback() // 邮箱格式正确，通过校验
  } else if (phonePattern.test(value)) {
    callback() // 手机号格式正确，通过校验
  } else {
    callback(new Error()) // 格式不正确，不通过校验
  }
}

const loginform=reactive({
	username:'',
	password:''
})
const checked = reactive({
	check:false
})
const formObj=ref()
const rules=reactive({
	username:[
		{ required:true, message:'请输入手机号/电子邮箱', tigger:'blur' },
		{ validator:validateUsername,message: '请输入正确的手机号或电子邮箱', trigger: 'blur'}
	],
	password:[
		{ required:true, message:'请输入登录密码', tigger:'blur' }
	]
})

const errorCount = ref(0);
const lockTime = ref(null);
 
function login(){
	const now = new Date().getTime()
	if (lockTime.value && now < lockTime.value) {
	    const remainingTime = Math.ceil((lockTime.value - now) / 1000)
	    // alert(`账号锁定中，请稍等 ${remainingTime} 秒`)
		ElMessage({
			message:'账号锁定中，请稍等 ' + remainingTime + ' 秒',
			type:'error'
		})
	    return
	  }
	formObj.value.validate(valid => {
		if(valid){
			const formData = new FormData()
			for(const key in loginform){
				formData.append(key,loginform[key])
			}
			userLoading.setLoading(true)
			_axios.request({
				url: '/admin/login',
				method: 'post',
				data:formData
			}).then(response => {
				if (response.data.code === 200) {
					// callback(response.data.content)
					errorCount.value = 0
					if(checked.check){
						VueCookie.set('token',response.data.content.token,{expires: 7 })
					}else{
						VueCookie.set('token',response.data.content.token,{expires: '1D' })
					}
					menuStore.setMenu(response.data.content.menu)
					idStore.setUserId(response.data.content.id)
					areaStore.setUserArea(response.data.content.areaId)
					if(response.data.content.areaId !== -1){
						router.push({
							path:'/index'
						})
					}else{
						router.push({
							path:'/center'
						})
						ElMessageBox.alert('请完善个人信息','提示',{
							confirmButtonText: '确认',
						})
					}
				} else {
					ElMessage.error(response.data.message)
					errorCount.value++
					if (errorCount.value > 3) {
					    lockTime.value = new Date().getTime() + 1 * 60 * 1000
						ElMessage({
							message:'输入错误次数过多，账号已锁定 5 分钟',
							type:'error'
						})
					    errorCount.value = 0
					}
				}
			}).catch(error => {
				console.dir(error)
			}).finally(() => {
				userLoading.setLoading(false)
			})
		}
	})
	
}
</script>

<style scoped lang="scss">
.title{
	text-align: center;
	margin-top: 20px;
	letter-spacing: 1.5rem;
	color: #fff;
}
</style>